<?php
class Commandes extends CI_Controller {
	private $ncommande;
	private $dcommande;

	public function index($page = 'commandes')
	{
		$ncommande = "NULL";
		if ( ! file_exists('application/views/commandes/'.$page.'.php'))
		{
			// Whoops, we don't have a page for that!
			show_404();
		}

		if(!isset($this->session->userdata['id'])) {
			show_error("Page interdite sans identification !!");
		}

		$this->load->helper('form');

		$aData = array(
			'set_columns' => array(
		array(
					'label' => 'Date',
					'name' => 'datejma',
					'width' => 100,
					'size' => 10
		),
		array(
					'label' => 'Nom responsable',
					'name' => 'responsable',
					'width' => 300,
					'size' => 10
		),
		array(
					'label' => 'Status',
					'name' => 'status',
					'width' => 160,
					'size' => 10
		),
		array(
					'label' => 'Montant',
					'name' => 'montant',
					'width' => 100,
					'align' => 'right',
					'size' => 10,
					'formatter' => 'currency'
					)
					),
			'div_name' => 'commandes_grid',
			'source' => 'commandes/commandesListe/',
			'sort_name' => 'date',
			'caption' => 'Commandes',
			'primary_key' => 'date',
			'pager' => 'pager',
			'functionDblClick' => 'dblClick',
			'functionSelectRow' => 'selectRow',
			'grid_height' => 450
					);

					$this->load->library('form_validation');

					$this->form_validation->set_rules('NCommande', '', 'callback_isNumCommande');

					if(!$this->form_validation->run()) {
						$data['commandesGrille'] = buildGrid($aData);
						$data['connecte'] = $this->session->userdata['prenom'].' '.$this->session->userdata['nom'];
						$data['iduser'] = $this->session->userdata['id'];
						$data['admin'] = $this->session->userdata['admin'];
						$data['uri'] = $this->uri->segment(1);
							
						$this->load->model('commandes_model','DBCommande', TRUE);
						$data['en_prep'] = $this->DBCommande->count("statutId", "01"); // Des commandes sont déjà en préparation ?
							
						$par = "";
							
						// Lecture du pdf de publicité
						$this->load->model('params_model', 'DBParams', TRUE);
						$where = array('parametre' => 'pub_date_debut');
						$dp = $this->DBParams->read('valeur', $where);
						$dpa = $dp->result();
						if(empty($dpa)) { $par = $par." pub_date_debut"; } else { $data['pub_date_debut'] = $dpa['0']->valeur; }
							
						$where = array('parametre' => 'pub_date_fin');
						$dp = $this->DBParams->read('valeur', $where);
						$dpa = $dp->result();
						if(empty($dpa)) { $par = $par." pub_date_fin"; } else { $data['pub_date_fin'] = $dpa['0']->valeur; }
							
						$where = array('parametre' => 'pub_pdf');
						$dp = $this->DBParams->read('valeur', $where);
						$dpa = $dp->result();
						if(empty($dpa)) { $par = $par." pub_pdf"; } else { $data['pub_pdf'] = $dpa['0']->valeur; }

						$where = array('parametre' => 'pub_largeur');
						$dp = $this->DBParams->read('valeur', $where);
						$dpa = $dp->result();
						if(empty($dpa)) { $par = $par." pub_largeur"; } else { $data['pub_largeur'] = $dpa['0']->valeur; }
							
						$where = array('parametre' => 'pub_hauteur');
						$dp = $this->DBParams->read('valeur', $where);
						$dpa = $dp->result();
						if(empty($dpa)) { $par = $par." pub_hauteur"; } else { $data['pub_hauteur'] = $dpa['0']->valeur; }
							
						if(strlen($par) > 0) {
							$commande_a_jour = array(
					'message' => '<font color="red">ERREUR</font> - Paramètres non trouvés : <br><font color="blue">'.$par.'</font>',
					'mes_aff' => 'O');
							$this->session->set_userdata($commande_a_jour);
						}

						$data['fromlogin'] = $this->session->userdata['fromlogin'];

						$this->load->library('layout');
						$this->layout->set_titre('RAVIOLES');
						$this->layout->ajouter_css('ravioles');
						$this->layout->ajouter_css('jquery-ui');
						$this->layout->ajouter_css('ui.jqgrid');
						$this->layout->ajouter_css('jquery.fancybox-1.3.4');
						$this->layout->ajouter_js('jquery');
						$this->layout->ajouter_js('jquery.corner');
						$this->layout->ajouter_js('jquery-ui');
						$this->layout->ajouter_js('grid.locale-fr');
						$this->layout->ajouter_js('jquery.jqgrid');
						$this->layout->ajouter_js('jquery.fancybox.pack');
						$this->layout->ajouter_js('jquery.fancybox-1.3.4.pack');
						$this->layout->views('templates/header', $data)
						->views('commandes/commandes',$data)
						->view('templates/footer', $data);
					} else {
						$Btn = $this->input->post('BCommandes');
						if($Btn == "Déconnexion") { redirect('login'); }
						if($Btn == "Créer commande groupée") { // Création nouvelle commande puis
							$this->load->model('commandes_model','DBCommande', TRUE);
							$commande = array(
					'date'     => date('Y-m-d'),
					'userId'   => $this->session->userdata['id'],
					'montant'  => 0,
					'statutId' => '01'
					);
					$commande2 = array();
					$resultat = $this->DBCommande->create($commande, $commande2);
					if($resultat != "NULL") {
						$resultat = str_pad($resultat, 5, '0', STR_PAD_LEFT);
						log_message('info', '### Commande '.$resultat.' créée avec succès. ###');
						$commande_a_jour = array(
						'message' => 'Nouvelle commande N&deg; '.$resultat.' cr&eacute;&eacute;e avec succ&egrave;s.',
						'mes_aff' => 'O');
						$this->session->set_userdata($commande_a_jour);
						$this->ncommande = $resultat;
						$this->session->set_userdata(array('NCommande' => $this->ncommande));
							
						// Envoi d'un mail général
						$this->load->model('params_model', 'DBParams', TRUE);
						$where = array('parametre' => 'url');
						$dp = $this->DBParams->read('valeur', $where);
						$dpa = $dp->result();
						$url_ravioles = $dpa['0']->valeur;
						$this->load->model('login_model', 'DBLogin', TRUE);
						$dbl = $this->DBLogin->read('email');
						$logins = $dbl->result_array();
						$this->load->helper('envoimail');
						foreach($logins as $login) {
							$data_email = array('email' => $login['email'],'url' => $url_ravioles);
							EnvoiMail('NEWCOMMANDE', $data_email);
							log_message('debug', '### Envoi Email de création de commande à '.$login['email'].' ###');
						}
							
						redirect('lignes');
					} else {
						$commande_a_jour = array(
						'message' => 'Echec de la cr&eacute;ation de la nouvelle commande !!',
						'mes_aff' => 'O');
						$this->session->set_userdata($commande_a_jour);
						redirect('commandes');
					}
						}
						if($Btn == "Entrer ma commande") { // Modification d'une commande
							$this->commande = $this->input->post('NCommande');
							$this->session->set_userdata(array('NCommande' => $this->ncommande));
							redirect('lignes');
						}
						if($Btn == "Voir ma commande") { // Modification d'une commande
							$this->commande = $this->input->post('NCommande');
							$this->session->set_userdata(array('NCommande' => $this->ncommande));
							redirect('/commandes/commandeVoir/');
						}						
						if($Btn == "Gérer commande") { // Gestion d'une commande
							$this->ncommande = $this->input->post('NCommande');
							if($this->ncommande != "NULL") {
								$this->session->set_userdata(array('NCommande' => $this->ncommande));
								redirect('/commandes/commandeAdmin/');
							} else { // Aucune commande sélectionnée
								$commande_a_jour = array(
						'message' => 'Il faut s&eacute;lectionner une commande !!',
						'mes_aff' => 'O');
								$this->session->set_userdata($commande_a_jour);
								redirect('commandes');
							}
						}
					}
	}

	public function commandesListe() {
		buildGridData(array(
				'model' => 'commandes_model',
				'method' => 'commandesJqgrid',
				'pkid' => 'id',
				'columns' => array( 'datejma','responsable','statut','montant' )
		)
		);
	}

	function isNumCommande($numCache) {
		$retour = TRUE;
		$Btn = $this->input->post('BCommandes');
		$this->ncommande = $numCache;
		if($Btn == "Entrer votre commande" && $numCache == "NULL") {
			$retour = FALSE;
		}
		return $retour;
	}
	
	function commandeVoir() {
		$ncommande = "NULL";

		if(!isset($this->session->userdata['id'])) {
			show_error("Page interdite sans identification !!");
		}

		$Btn = $this->input->post('BCommandeVoir');

		if(empty($Btn)) {
			// On remplit un tableau avec la commande en cours de l'utilisateur connecté
			$this->load->model('lignes_model', 'DBLigne', TRUE);
			$listeArticles = $this->DBLigne->commandeUser($this->session->userdata['NCommande'], $this->session->userdata['id']);

			$data['listeArticles'] = $listeArticles;
			
			$data['fromlogin'] = $this->session->userdata['fromlogin'];
	
			$this->load->library('layout');
			$this->layout->set_titre('RAVIOLES');
			$this->layout->ajouter_css('ravioles');
			$this->layout->ajouter_css('jquery-ui');
			$this->layout->ajouter_css('ui.jqgrid');
			$this->layout->ajouter_js('jquery');
			$this->layout->ajouter_js('jquery.corner');
			$this->layout->views('templates/header', $data)
						 ->views('commandes/visualiser',$data)
						 ->view('templates/footer', $data);
		} else {
			if($Btn == "Retour") { redirect('commandes'); }
		}
				
	}

	function commandeAdmin() {
		$feuilleExcel = "";
		$this->ncommande = $this->session->userdata('NCommande');
		$this->load->model('commandes_model', 'DBCommande', TRUE); // On va lire la date dans la base de données
		$where = array('id' => $this->ncommande);
		$dc = $this->DBCommande->read('date', $where);
		log_message('debug', '### Numéro de commande : '.$this->ncommande);
		$dca = $dc->result();
		$this->session->set_userdata(array('DCommande' => $dca['0']->date));

		$this->load->helper('form');

		$Btn = $this->input->post('BAdminCommande');

		if(!empty($Btn)) {
			if($Btn == "Retour") { redirect('commandes'); }
			if(strpos($Btn, "Vers") == 0) {
				$this->load->model("statuts_model", "DBStatut", TRUE);
				$this->load->model("commandes_model", "DBCommande", TRUE);

				$resultat = $this->DBCommande->read('statutId', array('id' => $this->ncommande));
				$statut = $resultat->result();

				$resultat = $this->DBStatut->read('suivantId', array('id' => $statut['0']->statutId));
				$suivant = $resultat->result();

				$this->DBCommande->update(array('id' => $this->session->userdata('NCommande')), array('statutId' => $suivant['0']->suivantId));

				$resultat = $this->DBStatut->read('libelle', array('id' => $suivant['0']->suivantId));
				$suivant = $resultat->result();
					
				log_message('info', '### Le statut de la commande '.$this->session->userdata('NCommande').' a évolué vers le statut '.$suivant['0']->libelle.' ###');
			}
			
			if($Btn == "Générer Excel") {
				$feuilleExcel = $this->genererExcel($this->session->userdata('NCommande'));
				log_message('debug', '### Generation de la feuille Excel terminee ! ###');
				
				if(strlen($feuilleExcel) > 0) { 
					$this->load->helper('download');
					force_download('Commande_Truchet_'.date('Y-m-d').'.xls', $feuilleExcel);
				}		
			}

			$commande_a_jour = array(
					'message' => 'Nouveau statut de la commande '.$this->session->userdata('NCommande').'<br><br><font color=red>'.$suivant['0']->libelle.'.</font>',
					'mes_aff' => 'O');
			$this->session->set_userdata($commande_a_jour);
		}

	$this->load->model("commandes_model", "DBCommande", TRUE);

	$total = $this->DBCommande->totalCommande($this->ncommande);

	$resultat = $this->DBCommande->read('statutId', array('id' => $this->ncommande));
	$statut = $resultat->result();

	$this->load->model("statuts_model", "DBStatut", TRUE);
	$resultat = $this->DBStatut->read('libelle', array('id' => $statut['0']->statutId)); // On recherche le libellé du statut courant
	$statut2 = $resultat->result();
	$lstatut = $statut2['0']->libelle;
	$resultat = $this->DBStatut->read('suivantId', array('id' => $statut['0']->statutId)); // On recherche le libellé du statut suivant
	$suivant = $resultat->result();
	if(isset($suivant['0']->suivantId)) {
		$resultat = $this->DBStatut->read('libelle', array('id' => $suivant['0']->suivantId));
		$suivant = $resultat->result();
		$lsuivant = $suivant['0']->libelle;
	} else { $lsuivant = "####"; }
		
	$aData = array(
			'set_columns' => array(
	array(
					'label' => 'Code',
					'name' => 'code',
					'width' => 60,
					'size' => 10,
					'align' => 'right'
					),
					array(
					'label' => 'Libell&eacute;',
					'name' => 'libelle',
					'width' => 300,
					'size' => 10
					),
					array(
					'label' => 'Poids (g)',
					'name' => 'poids',
					'width' => 60,
					'size' => 10,
					'align' => 'right'
					),
					array(
					'label' => 'Quantit&eacute;',
					'name' => 'nombre',
					'width' => 60,
					'size' => 3,
					'align' => 'right',
					'formatter' => 'integer',
					'editable' => true
					),
					array(
					'label' => 'PU TTC',
					'name' => 'pu',
					'width' => 80,
					'size' => 10,
					'formatter' => 'currency'
					),
					array(
					'label' => 'Montant',
					'name' => 'montant',
					'width' => 90,
					'align' => 'right',
					'size' => 10,
					'formatter' => 'currency'
					)
					),
			'div_name' => 'lignes_commande_grid',
			'source' => 'commandes/allLignes/',
			'sort_name' => 'id',
			'caption' => 'Commande N\260 '.$this->ncommande.' du '.MySQL2FR($this->session->userdata('DCommande')).' - '.$lstatut,
			'primary_key' => 'id',
			'loadonce' => 'true',
			'functionDblClick' => 'cdblClick',
			'functionSelectRow' => 'cselectRow',
			'loadComplete' => 'afterLoading',
			'pager' => 'pager',
			'grid_height' => 450
					);

					$uData = array(
			'set_columns' => array(
					array(
					'label' => 'Nom',
					'name' => 'nomprenom',
					'width' => 220,
					'size' => 10
					),
					),
			'div_name' => 'users_commande_grid',
			'source' => 'commandes/usersCommande/',
			'sort_name' => 'id',
			'caption' => 'Personnes ayant command\351',
			'primary_key' => 'id',
			'functionDblClick' => 'udblClick',
			'functionSelectRow' => 'uselectRow',
			'pager' => 'upager',
			'grid_height' => 450
					);

					$data['lignesCommandeGrille'] = buildGrid($aData);
					$data['usersCommandeGrille'] = buildGrid($uData);
					$data['suivant'] = $lsuivant;
					$data['total'] = $total['montant'];
					$data['connecte'] = $this->session->userdata['prenom'].' '.$this->session->userdata['nom'];
					$data['iduser'] = $this->session->userdata['id'];
					$data['admin'] = $this->session->userdata['admin'];
					$data['uri'] = $this->uri->segment(1);

					$this->load->library('layout');
					$this->layout->set_titre('RAVIOLES');
					$this->layout->ajouter_css('ravioles');
					$this->layout->ajouter_css('jquery-ui');
					$this->layout->ajouter_css('ui.jqgrid');
					$this->layout->ajouter_js('jquery');
					$this->layout->ajouter_js('jquery.corner');
					$this->layout->ajouter_js('jquery-ui');
					$this->layout->ajouter_js('grid.locale-fr');
					$this->layout->ajouter_js('jquery.jqgrid');
					$this->layout->views('templates/header', $data)
					->views('commandes/administration',$data)
					->view('templates/footer', $data);
}

public function allLignes() {
	buildGridData(array(
				'model' => 'lignes_model',
				'method' => 'allLignesJqgrid',
				'pkid' => 'id',
				'columns' => array( 'code', 'libelle', 'poids', 'nombre', 'pu', 'montant' )
	)
	);
}

public function usersCommande() {
	buildGridData(array(
				'model' => 'login_model',
				'method' => 'usersCommandeJqgrid',
				'pkid' => 'id',
				'columns' => array( 'nomprenom' )
	)
	);
}

public function userLignes($user) {
	$this->session->set_userdata(array('user_requete' => $user));
	buildGridData(array(
				'model' => 'lignes_model',
				'method' => 'userLignesJqgrid',
				'pkid' => 'id',
				'columns' => array( 'code', 'libelle', 'poids', 'nombre', 'pu', 'montant' )
	)
	);
}

private function genererExcel($NCommande) {
	log_message('debug','### Generation de la feuille Excel ###');
	// Charger la commande dans un tableau
	$this->load->model('lignes_model', 'DBLigne', TRUE);
	$ExcelCommande = $this->DBLigne->recapCommandePourExcel($NCommande); // Extraction de la commande par code artcile : code article et nombre

	// Lire les paramètres xls
	$this->load->model('params_model', 'DBParams', TRUE);

	$where = array('parametre' => 'xls_ligne');
	$dp = $this->DBParams->read('valeur', $where);
	$dpa = $dp->result();
	$xls_ligne = $dpa['0']->valeur;

	$where = array('parametre' => 'xls_ligne_fin');
	$dp = $this->DBParams->read('valeur', $where);
	$dpa = $dp->result();
	$xls_ligne_fin = $dpa['0']->valeur;

	$where = array('parametre' => 'xls_colonne');
	$dp = $this->DBParams->read('valeur', $where);
	$dpa = $dp->result();
	$xls_colonne = $dpa['0']->valeur;

	$where = array('parametre' => 'xls_colonne_article');
	$dp = $this->DBParams->read('valeur', $where);
	$dpa = $dp->result();
	$xls_colonne_article = $dpa['0']->valeur;

	$where = array('parametre' => 'xls_modele');
	$dp = $this->DBParams->read('valeur', $where);
	$dpa = $dp->result();
	$xls_modele = $dpa['0']->valeur;

	$where = array('parametre' => 'xls_final');
	$dp = $this->DBParams->read('valeur', $where);
	$dpa = $dp->result();
	$xls_final = $dpa['0']->valeur;

	$where = array('parametre' => 'xls_feuille');
	$dp = $this->DBParams->read('valeur', $where);
	$dpa = $dp->result();
	$xls_feuille = $dpa['0']->valeur;

	$where = array('parametre' => 'xls_version');
	$dp = $this->DBParams->read('valeur', $where);
	$dpa = $dp->result();
	$xls_version = $dpa['0']->valeur;

	// Ouvrir la feuille modèle et en balayer les articles

	//Initialiser PHPExcel
	set_include_path(get_include_path() . PATH_SEPARATOR . 'application/third_party/');
	include 'PHPExcel/IOFactory.php';

	//Ouvrir la feuille Excel
	$xlsFile = $xls_modele;

	$inputFileType = PHPExcel_IOFactory::identify($xlsFile);  // Identifier le type de fichier Excel
	$objReader = PHPExcel_IOFactory::createReader($inputFileType); // Créer un objet de lecture
	$Classeur = $objReader->load($xlsFile); // Charger le fichier Excel
	$Feuille = $Classeur->getSheetByName($xls_feuille); // Objet vers la feuille

	// Balayage des articles
	$ligne = intval($xls_ligne);
	do {
		$code_article = $Feuille->getCell($xls_colonne_article.strval($ligne)); // On récupère le code article dans le feuille Excel
		log_message('debug', '### Traitement de l\'article '.$code_article.' ###');
		foreach($ExcelCommande as $lcommande) {
			if($code_article == $lcommande['code']) { // Le code est présent dans la commande => on écrit dans la feuille Excel
				$Feuille->setCellValue($xls_colonne.$ligne, $lcommande['nombre']);
				log_message('debug', '### Article '.$code_article.' commandé - Quantité : '.$lcommande['nombre']);
				break;
			}
		}
		$ligne = $ligne + 1;
	}  while($ligne <= intval($xls_ligne_fin));

	// Mettre la feuille en téléchargement
	$xlsFichier = $xls_final.'_'.date('Y-m-d').'.xls';
	$objWriter = PHPExcel_IOFactory::createWriter($Classeur, $inputFileType); // Création de l'objet d'écriture
	$objWriter->save($xlsFichier);

	$xlsContenu = file_get_contents($xlsFichier); // Charger le contenu de la feuille Excel
	return $xlsContenu;
}

}
?>
